package pers.vic.basics.datastructure.array;

/**
 * @author Vic.xu
 * @description:
 * @date: 2020/10/15 11:03
 */
public class VicArray implements ArrayInterface<Integer> {

    /**
     * 保存数据的数组
     */
    private int[] array;

    /**
     * 容量
     */
    private int capacity;

    /**当前数据的长度*/
    private int size;

    private static final int DEFAULT_CAPACITY = 20;

    public VicArray() {
        this(DEFAULT_CAPACITY);
    }

    /**
     * 初始化数组
     */
    public VicArray(int capacity) {
        this.array = new int[capacity];
        this.capacity = capacity;
        this.size = 0;
    }


    @Override
    public boolean add(Integer element) {
        /*是否装满*/
        if (capacity <= size) {
            return false;
        }
        this.array[size++] = element;
        return true;
    }

    @Override
    public int search(Integer element) {
        for (int i = 0; i < size; i++) {
            if (array[i] == element) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public boolean delete(Integer element) {
        int index = search(element);
        if (index == -1) {
            return false;
        }

        //把当前值置为默认值
        array[index] = 0;
        // 删除此元素，后面的元素往前移动
        while (index < size - 1) {
            array[index] = array[++index];
        }
        array[size - 1] = 0;
        size--;

        return true;
    }

    @Override
    public Integer get(int index) {
        if (index < 0 || index >= size) {
            throw new IllegalStateException("数组下标越界");
        }
        return array[index];
    }

    @Override
    public boolean modify(Integer old, Integer element) {
        int index = search(old);
        if (index == -1) {
            System.out.println("不存在的数值:" + old);
            return false;
        }
        array[index] = element;
        return true;
    }

    @Override
    public void display() {
        for (int i = 0; i < size; i++) {
            System.out.print(array[i] + "\t");
        }
        System.out.println();
    }

    @Override
    public int size() {
        return size;
    }
}
